package com.rabiitmq.spring.ack;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author xiaochi
 * @date 2022/4/9 15:43
 * @desc TestListner 监听队列（ack）
 */
@Slf4j
@Component
//@RabbitListener(bindings =
//    @QueueBinding(
//            value = @Queue(value = "${mq.config.queue}",durable = "true"),
//            exchange = @Exchange(value = "${mq.config.exchange}",durable = "true",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
//            key = "#.#"
//    )
//)
public class TestListner {

    private ObjectMapper mapper = new ObjectMapper();

    //@RabbitListener(queues = "${mq.config.queue}")
    @RabbitListener(bindings =
        @QueueBinding(
            value = @Queue(value = "${mq.config.queue}",durable = "true"),
            exchange = @Exchange(value = "${mq.config.exchange}",durable = "true",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = "#.#"
        )
    )
    //public void listnerMsg(TestPojo testPojo, Message message, Channel channel) throws IOException {
    public void listnerMsg(Map<String, String> map, Message message, Channel channel) throws IOException {
        System.out.println("收到消息："+ map.toString());
        System.out.println("收到消息："+ map.get("id"));
        System.out.println("收到消息："+ map.get("name"));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            // 消费失败，重新入队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
